// packageH/newDraw/newDrawIndex/newDrawIndex.js
import {
  timeHandle
} from '../../../utils/dateTimePicker';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showcomment: false,
    showInfo: false,
    addNum: 1,
    showAddress: false,
    info: {},
    tel: "",
    addBtn_status: false, //是否可参加
    commentlist: [],
    comment_input: "",
    showWechatshar: false,
    showShare: false,
    options: [{
      name: "微信分享",
      icon: "wechat",
      openType: 'share'
    },
    {
      name: "分享海报",
      icon: "poster"
    }
    ],
    showposter: false,
    poster_url: "",
    activityInfo: {},
    addressData: [],
    //more(评论分页)
    isLoadMore: false,
    page: 1,
    total_page: 0,
    percent: 0,
    btn_text: '',
    goodsPopupShow: false,
    hand_goods_obj: {},
    activeid: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if(options.id){
      this.setData({
        activeid: options.id
      });
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(',');
        console.log(info_arr);

        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          // 这是自提点
          console.log(chil_arr);
          if (chil_arr[0] == 'id') {
            this.setData({
              activeid: chil_arr[1]
            });
          }
        }
      }
    }
    this.getData();
  },
  getData() {
    wx.showLoading({
      title: '加载中',
    });

    let that = this;
    let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.index.detail');
    app._postNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.activeid
      },
      success: (resdata) => {
        wx.hideLoading();
        let res = resdata.data;
        if (res.result == 1) {
          let percent = parseInt(Number((res.data.max_num - res.data.activity_num) / res.data.max_num) * 100);
          let text = "";
          this.setData({
            addBtn_status: false
          });
          let timestamp = new Date().getTime();
          if (res.data.start_time * 1000 > timestamp) {
            text = "活动未开始";
          } else if (res.data.activity_state == 3) {
            text = "活动已结束";
          } else if (res.data.member_num <= 0) {
            text = "您已参与";
          } else if (res.data.type_id == 2) {
            text = `￥${res.data.money}抽奖`;
            this.setData({
              addBtn_status: true
            });
          } else if (res.data.type_id == 1) {
            text = `免费`;
            this.setData({
              addBtn_status: true
            });
          }
          that.setData({
            info: res.data,
            percent: percent,
            btn_text: text
          });
          let _html = res.data.explain.replace(/<img/g, '<img style="width:100%;display: block;"');
          that.setData({
            ['info.explain']: _html
          });

        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        wx.hideLoading();
        console.log(res.msg);
      }
    });
  },
  getComment() {
    // 获取抽奖评论
    let that = this;
    let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.index.getComment');
    app._postNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.activeid
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({

            isLoadMore: true,
            total_page: res.data.last_page,
            showcomment: true
          });
          let commentlist = res.data.data;
          commentlist.forEach(item => {
            let d = new Date(item.created_at.replace(/-/g, '/')).getTime();
            item.created_at = timeHandle(d);
          });
          that.setData({
            commentlist
          });
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  closeComment() {
    this.setData({
      showcomment: false
    });
  },
  //获取更多数据
  getMoreData() {
    const that = this;
    if (!that.data.isLoadMore) {
      return;
    }
    this.setData({
      isLoadMore: true // 防止多次请求分页数据
    });
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      let _json = {
        activity_id: that.data.activeid
      };
      this.setData({
        page: this.data.page + 1
      });
      _json.page = this.data.page;
      let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.index.getComment');
      app._postNetWork({
        url: urlStr,
        data: _json,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            let myData = res.data.data;
            let commentlist = that.data.commentlist.concat(myData); //数组拼接
            that.setData({
              commentlist: commentlist,
              isLoadMore: true,
            });

          } else {
            let _pagea = that.data.page;
            that.setData({
              isLoadMore: false,
              page: _pagea - 1
            });
            wx.showToast({
              title: res.msg,
              duration: 1000,
              icon: 'none'
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        }
      });
    }
  },
  getCollection() {
    //收藏 or 取消收藏（1-收藏 0-取消收藏）
    let that = this;
    let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.index.collection');
    app._postNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.activeid,
        state: that.data.info.is_collection ? 0 : 1
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          title: res.msg,
          duration: 1000,
          icon: 'none'
        });
        if (res.result == 1) {
          that.setData({
            ['info.collection_num']: this.data.info.is_collection == 1 ? this.data.info.collection_num - 1 : this.data.info.collection_num + 1,
            ['info.is_collection']: !this.data.info.is_collection
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  addActivity() {
    if (!this.data.addBtn_status) {
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.team.getActivity');
    app._postNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.activeid
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            activityInfo: res.data,
            showInfo: true
          });
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  onClickRight() {
    this.setData({
      showInfo: false
    });
  },
  onChangeaddNum(event) {
    this.setData({
      addNum: event.detail
    });
  },
  onChangeTel(event) {
    this.setData({
      tel: event.detail
    });
  },
  joinActivity() {
    let that = this;
    //参加活动
    //如果是分享进入的，把分享人的id加上
    let json = {
      activity_id: that.data.activeid,
      total: this.data.addNum,
      address: JSON.stringify(this.data.activityInfo.address),
      pid: this.options.mid || 0
    };
    
    if (this.data.activityInfo.type == 2 && this.data.activityInfo.need_address == 1) {
      //虚拟商品并且开启不填写地址
      if (this.data.tel == '') {
        wx.showToast({
          title: '请填写手机号',
          duration: 1000,
          icon: 'none'
        });
        return;
      }
      json.address = JSON.stringify({
        mobile: this.data.tel
      });
    }else{
      if(Object.keys(this.data.activityInfo.address).length == 0){
        wx.showToast({
          title: '请选择收货地址',
          duration: 1000,
          icon: 'none'
        });
        return;
      }
    }
    // let _url = "";
    // 活动类型type_id 1-免费 2-付费
    if (this.data.activityInfo.type_id == 2) {
      //付费。跳转支付页，带参
      json.money = this.data.info.money;
      this.setData({
        showInfo: false
      });
      let datas = JSON.stringify(json);
      wx.navigateTo({
        url: '/packageH/newDraw/payment/payment?datas=' + datas
      });
      return;
    }
    let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.team.freeJoinActivity');
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          title: res.msg,
          duration: 1000,
          icon: 'none'
        });
        if (res.result == 1) {
          that.getData();
          that.setData({
            showInfo: false
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  onClickShowShare() {
    this.setData({
      showShare: true
    });
  },
  onCloseShare() {
    this.setData({
      showShare: false
    });
  },
  onClosePoster() {
    this.setData({
      showposter: false
    });
  },
  onSelectShare(event) {
    if (event.detail.name == '分享海报') {
      this.getPoster();
    }
    this.onCloseShare();
  },
  getPoster() {
    this.setData({
      showposter: true
    });
    return;
  },

  bindinputComment(event) {
    this.setData({
      comment_input: event.detail.value
    });
  },
  sendComment() {
    if (this.data.comment_input == "") {
      wx.showToast({
        title: '不能发送空白信息',
        duration: 1000,
        icon: 'none'
      });
      return;
    }
    let urlStr = app.getNetAddresss('plugin.luck-draw.frontend.index.comment');
    app._postNetWork({
      url: urlStr,
      data: {
        activity_id: this.data.activeid,
        content: this.data.comment_input
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            comment_input: ''
          });
          this.getComment();
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  gotoWinnersList() {
    wx.navigateTo({
      url: '/packageH/newDraw/winnersList/winnersList?id=' + this.data.activeid + '&num=' + this.data.info.current_round
    });
  },
  gotoLotteryComplaint() {
    wx.navigateTo({
      url: '/packageH/newDraw/lotteryComplaint/lotteryComplaint?id=' + this.data.activeid
    });
  },
  getAddress() {
    this.setData({
      showAddress: true
    });
  },
  confirmSelectAddress(e) {
    this.setData({
      ['activityInfo.address']: e.detail,
      showAddress: false
    });
  },
  getGoodsDetails(e) {
    let id = e.currentTarget.dataset.id;
    let urlStr = app.getNetAddresss('goods.goods.get-goods-page');
    app._postNetWork({
      url: urlStr,
      data: {
        id: Number(id)
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let time = (this.data.info.end_time * 1000 - (new Date().getTime()));
          res.data.get_goods.end_time = time>0?time:0;
          this.setData({
            goodsPopupShow: true,
            hand_goods_obj: res.data.get_goods
          });
        }
      }
    });
  },
  gotoLuckyDraw() {
    wx.navigateTo({
      url: '/packageH/newDraw/luckyDraw/luckyDraw'
    });

  },
  gotoMydraw() {
    wx.navigateTo({
      url: '/packageH/newDraw/mydraw/mydraw'
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.data.info.activity_name,
      path: '/packageH/newDraw/newDrawIndex/newDrawIndex?id=' + this.data.activeid + '&mid=' + mid
    };
  }
});